How to manage complex run state
If your model contains a large number of state variables, declare them inside a class. The state class can be placed in the business-logic subdirectory of your model.
Declaring your state variables inside a class allows you to manage all of them as one - an instance of the state class. For example:
- Save all the variable values with a single call to
Epicenter.record(). - Add all the state variables to snapshot restore with a single line in the context file.
Save the state variable
In the following example, we are saving all the state variables encapsulated in an instance of a class called state:
Epicenter.record("state", state)
This approach is more efficient than saving each variable separately.
The variables that comprise the run state are stored in JSON format. So, the state class would be serialized as a JSON object with JSON Pickle. To achieve this, include code similar to the snippet below in your model to encode and decode state into JSON.
import jsonpickle
from epicenter import Epicenter
# Declare an encoder function
def state_encoder(variable):
return jsonpickle.encode(variable, unpicklable=True)
# Declare a decoder function
def state_decoder(name, variable, value, mode):
global state
state = jsonpickle.decode(value)
# Register the functions with Epicenter
Epicenter.register_custom_encoder(State, state_encoder)
Epicenter.register_custom_decoder(State, state_decoder)
Restore the state variable
In the example below, we are enabling snapshot restore of a single variable called state, assuming that all state variables for the model are encapsulated in a class.
{
"language": "python3",
"restorations": {
"assembly": [
{
"snapshot": {
"variables": [
"state"
]
}
}
]
}
}